import {main, subMain, basicView,projectView} from './lazyLoading.js';
import config from '@/config/index'
import {GetMenu} from '@/projects/basic/api/admin/menu'
import {getDynamicOpenTab} from "@/libs/menu/util";
import {genDynamicRoute} from "@/libs/tools"
import {listAllCacheDicData} from "@/projects/basic/api/admin/datadic"
let util = {};
//开发环境添加demo菜单
if (process.env.NODE_ENV === 'development') {
    util.addMenu = [{
        component: main(),
        title: '组件demo',
        name: '组件demo',
        icon: 'ios-build',
        path: '/demo',
        meta: {
            permTypes: null,
            title: '组件demo',
            name: '组件demo',
            keepAlive: true,
            icon: 'ios-build'
        },
        children: [
            {
                component: ()=>import('@/demo/table-form/table-form-demo'),
                title: '表格和表单demo',
                name: '表格和表单demo',
                icon: 'ios-basket',
                path: '/ruiFromAndTableDemo',
                meta: {
                    permTypes: null,
                    title: '表格和表单demo',
                    name: '表格和表单demo',
                    keepAlive: true,
                    icon: 'ios-basket'
                },
            },
            {
                component: ()=>import('@/demo/rules/Rule-tree'),
                title: '规则控件demo',
                name: '规则控件demo',
                icon: 'ios-basket',
                path: '/ruleCom',
                meta: {
                    permTypes: null,
                    title: '规则控件demo',
                    name: '规则控件demo',
                    keepAlive: true,
                    icon: 'ios-basket'
                },
            },
            {
                component: ()=>import('@/demo/tab/tab-demo'),
                title: 'tab',
                name: 'tabdemo',
                icon: 'ios-basket',
                path: '/tabdemo',
                meta: {
                    permTypes: null,
                    title: 'tab',
                    name: 'tab',
                    menusParams:{'menu':'menu','meii':'sss'},
                    keepAlive: true,
                    icon: 'ios-basket'
                },
            },
            {
                component: ()=>import('@/projects/basic/pages/admin/holiday/holiday'),
                title: '节假日',
                name: 'holiday',
                icon: 'ios-basket',
                path: '/holiday',
                meta: {
                    permTypes: null,
                    title: '节假日',
                    name: 'holidayadd',
                    keepAlive: true,
                    icon: 'ios-basket'
                },
            },
            {
                component: ()=>import('@/demo/auth/auth'),
                title: '权限',
                name: 'auth',
                icon: 'ios-basket',
                path: '/auth',
                meta: {
                    permTypes: null,
                    title: '权限',
                    name: 'authdemo',
                    keepAlive: true,
                    icon: 'ios-basket'
                },
            },
            {
                component: ()=>import('@/projects/basic/pages/batch/index'),
                title: '批量',
                name: 'batch',
                icon: 'ios-basket',
                path: '/batch',
                meta: {
                    permTypes: null,
                    title: '批量',
                    name: 'batch-demo',
                    keepAlive: true,
                    icon: 'ios-basket'
                },
            }
        ]
    },
]
}

util.title = function (title) {
    title = title ? ("-" + title) : '';
    window.document.title = config.getTitle() + title;
};
util.checkLogin=function(token,time){
    if (token === null || token === undefined||token==''||time == null||time==NaN || time === undefined || time < 15) {
        return false;
    }
    return true;
}
util.initSystem = function (vm) {
    const constRoutes = [];
    const otherRoutes = [];

    // 判断用户是否登录
    let token = vm.$store.getters.access_token;
    let time = (vm.$store.getters.expires_in-(Date.now))/1000;
    if (!util.checkLogin(token,time)) {
        // 未登录
        return;
    }
    listAllCacheDicData();
    GetMenu().then((res) => {
        vm.$store.commit("setHasLogin",true)
        let menuData = res.data;
        if (menuData === null || menuData === "" || menuData === undefined) {
            return;
        }
        util.initRouterNode(constRoutes, menuData);
        // 添加其他路由到主界面
        if (util.addMenu) {
            constRoutes.push(...util.addMenu)
        }

        getDynamicOpenTab().forEach(tab=>{
            otherRoutes.push(genDynamicRoute(tab.meta.name,tab.meta.componentPath,tab.meta.title,tab.meta.icon,tab.meta.params,tab.meta.dIndex,tab.meta.permTypes,tab.meta.isFull,null,tab.meta.menusParams))
        });
        // util.initRouterNode(otherRoutes, otherRouter);
        // 添加主界面路由
        vm.$store.commit('updateAppRouter', constRoutes.filter(item => {
            return item.children.length > 0
        }));
        // 刷新界面菜单
        vm.$store.commit('updateMenuList', constRoutes.filter(item => item.children.length > 0));
        // 添加全局路由
        vm.$store.commit('updateDefaultRouter', otherRoutes);
    })
};

// 生成路由节点
util.initRouterNode = function (routers, data) {
    for (let item of data) {
        let menu = Object.assign({}, item);
        if (menu.component == 'Main') {
            menu.component = main()
        } else if (menu.component == 'SubMain') {
            menu.component = subMain()
        } else {
            if(menu.basic=='Y') {
                menu.component = basicView(menu.component);
            }else{
                menu.component = projectView(menu.component);
            }
            //暂时写死basic 后台配置好了改成动态获取
        }
        if (item.children && item.children.length > 0) {
            menu.children = [];
            util.initRouterNode(menu.children, item.children);
        }
        let meta = {};
        // 给页面添加权限、标题、第三方网页链接
        meta.permTypes = menu.permTypes ? menu.permTypes : null;
        meta.title = menu.title ? menu.title : '页面';
        meta.url = menu.url ? menu.url : null;
        meta.keepAlive = true;
        meta.icon = item.icon;
        meta.dynamicTab = false
        menu.meta = meta;
        menu.icon = meta.icon
        if(item.params){
            menu.meta.params = JSON.parse(item.params)
            menu.meta.menusParams = JSON.parse(item.params)
        }
        routers.push(menu);
    }
};

util.toDefaultPage = function (routers, name, route, next) {
    let len = routers.length;
    let i = 0;
    let notHandle = true;
    while (i < len) {
        if (routers[i].name === name && routers[i].children && routers[i].redirect === undefined) {
            route.replace({
                name: routers[i].children[0].name
            });
            notHandle = false;
            next();
            break;
        }
        i++;
    }
    if (notHandle) {
        next();
    }
};
util.debounce = function (func, wait, immediate) {
    let timeout, args, context, timestamp, result

    const later = function () {
        // 据上一次触发时间间隔
        const last = +new Date() - timestamp

        // 上次被包装函数被调用时间间隔last小于设定时间间隔wait
        if (last < wait && last > 0) {
            timeout = setTimeout(later, wait - last)
        } else {
            timeout = null
            // 如果设定为immediate===true，因为开始边界已经调用过了此处无需调用
            if (!immediate) {
                result = func.apply(context, args)
                if (!timeout) context = args = null
            }
        }
    }
};

util.formatDate = function (date, fmt = 'YYYY-MM-DD hh:mm:ss') {
    if (!(date instanceof Date)) {
        date = new Date(date)
    }
    let padLeftZero = (str) => {
        return ('00' + str).substr(str.length)
    }
    let doFormatDate = (date, fmt) => {
        if (/(Y+)/.test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1,
                (date.getFullYear() + '').substr(4 - RegExp.$1.length)
            )
        }
        let obj = {
            'M+': date.getMonth() + 1,
            'D+': date.getDate(),
            'h+': date.getHours(),
            'm+': date.getMinutes(),
            's+': date.getSeconds()
        }
        for (let k in obj) {
            if (new RegExp(`(${k})`).test(fmt)) {
                let str = obj[k] + ''
                fmt = fmt.replace(
                    RegExp.$1,
                    RegExp.$1.length === 1 ? str : padLeftZero(str)
                )
            }
        }
        return fmt
    }

    return doFormatDate(date, fmt)
}

export default util;
